<?php
// +----------------------------------------------------------------------
// | 文件: index.php
// +----------------------------------------------------------------------
// | 功能: 提供todo api接口
// +----------------------------------------------------------------------
// | 时间: 2021-11-15 16:20
// +----------------------------------------------------------------------
// | 作者: rangangwei<gangweiran@tencent.com>
// +----------------------------------------------------------------------

namespace app\controller;

use Error;
use Exception;

use app\model\Counters;
use think\response\Html;
use think\response\Json;
use app\model\Users;
use think\facade\Db;
use app\model\RoomElectricityMeter;
use think\facade\Log;
use think\Request;
//use think\facade\Request;

class Index
{

    /**
     * /api/checkin
     * 登记入住信息
     * @return void
     */
    public function checkin(){
        Db::startTrans(); //开启事务

        $openid = request()->param("openid");
        $name = request()->param("name");
        $room = request()->param("room");
        $bumen = request()->param("bumen");
        $phone = request()->param("phone");


        try{
            $users = new Users();
            $usedata = [
                "wx_openid"=>$openid,
                "name"=>$name,
                "phone"=>$phone,
                "bumen"=>$bumen,
                "room_id"=>$room
            ];
            $id=$users->save($usedata);
            Db::commit();
            return \json(['code'=>200,'msg'=>'添加成功','detail'=>['id'=>$id]]);

        }catch (\Exception $e){
            Db::rollback();
            return \json(['code'=>0,'msg'=>'失败，事务回滚']);
        }
    }
    /**
     * @var \think\Request Request实例
     */
    protected $request;
    /**
     * 构造方法注入 请求
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }
    /**
     * 主页静态页面
     * @return Html
     */
    public function index(): Html
    {
        # html路径: ../view/index.html
        return response(file_get_contents(dirname(dirname(__FILE__)).'/view/index.html'));
    }
    /**
     * 测试更新电表
     */
    public function updatedb(){
       try {
           $room_num = $this->request->post('room_num');
           $electricity_meter = $this->request->post('electricity_meter');
            //$room_num = Request::post('room_num');
            //$electricity_meter = Request::post('electricity_meter');

            if (empty($room_num) || empty($electricity_meter)) {
                throw new Exception('参数不完整');
                //测试测试
            }

            $REM = new RoomElectricityMeter();

           $REM->room_num = $room_num;
           $REM->electricity_meter = $electricity_meter;
           $REM->save();

            if ($REM) {

                return json(['code' => 0, 'msg' => '更新成功']);
            } else {
                return json(['code' => 1, 'msg' => '房间不存在']);
            }
        } catch (Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }


    /**
     * 获取todo list
     * @return Json
     */
    public function getCount()
    {

        try{
            $REM   = new RoomElectricityMeter;
            $REM->test_add(101);

        }catch (Exception $e) {
            $res = [
                "code" => -1,
                "data" => [],
                "errorMsg" => ("获取计数异常" . $e->getMessage())
            ];
            Log::write('getCount rsp: '.json_encode($res));
            return json($res);
        }
    }


    /**
     * 根据id查询todo数据
     * @param $action `string` 类型，枚举值，等于 `"inc"` 时，表示计数加一；等于 `"reset"` 时，表示计数重置（清零）
     * @return Json
     */
    public function updateCount($action): Json
    {
        try {
            if ($action == "inc") {
                $data = (new Counters)->find(1);
                if ($data == null) {
                    $count = 1;
                }else {
                    $count = $data["count"] + 1;
                }
    
                $counters = new Counters;
                $counters->create(
                    ["count" => $count, 'id' => 1],
                    ["count", 'id'],
                    true
                );
            }else if ($action == "clear") {
                Counters::destroy(1);
                $count = 0;
            }

            $res = [
                "code" => 0,
                "data" =>  $count
            ];
            Log::write('updateCount rsp: '.json_encode($res));
            return json($res);
        } catch (Exception $e) {
            $res = [
                "code" => -1,
                "data" => [],
                "errorMsg" => ("更新计数异常" . $e->getMessage())
            ];
            Log::write('updateCount rsp: '.json_encode($res));
            return json($res);
        }
    }
}
